﻿using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using Sharp.UnusedReferences.Options;
using Sharp.UnusedReferences.Helpers;
using Sharp.UnusedReferences.EventsListeners;

namespace Sharp.UnusedReferences
{
	/// <summary>
	/// This is the class that implements the package exposed by this assembly.
	///
	/// The minimum requirement for a class to be considered a valid package for Visual Studio
	/// is to implement the IVsPackage interface and register itself with the shell.
	/// This package uses the helper classes defined inside the Managed Package Framework (MPF)
	/// to do it: it derives from the Package class that provides the implementation of the 
	/// IVsPackage interface and uses the registration attributes defined in the framework to 
	/// register itself and its components with the shell.
	/// </summary>
	// This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is a package.
	[PackageRegistration(UseManagedResourcesOnly = true)]
	// This attribute is used to register the informations needed to show the this package
	// in the Help/About dialog of Visual Studio.
	[InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 2)]
	// This attribute is needed to let the shell know that this package exposes some menus.
	[ProvideMenuResource("Menus.ctmenu", 1)]
	[ProvideToolWindow(typeof(ToolWindowSolutionTree))]
	[Guid(GuidList.guidTWToolbarPkgString)]
	[ProvideOptionPage(typeof(DialogPageOptionsGeneral), "Unused References Removal", "General", 0, 0, true)]
	[ProvideOptionPage(typeof(DialogPageOptionsReset), "Unused References Removal", "Reset", 0, 0, true)]
	[ProvideAutoLoad(UIContextGuids.SolutionHasSingleProject)]
	[ProvideAutoLoad(UIContextGuids.SolutionHasMultipleProjects)]
	public sealed class PackageUnusedReferences : Package
	{
		#region Fields

		public const string ProductName = "Unused References Scanner";
		IVsOutputWindowPane MyOutputWindowPane;
		private const string stringSolutionConfigurationSuffix = " (96057F62-CE05-4A1A-90A5-AC96603DCF2E)";
		Hashtable HashtableProjectUsedReferencedAssemblis = new Hashtable();
		DTE2 dte;
		DialogPageOptionsGeneral Options;
		OleMenuCommand OleMenuCommandShowToolWindow;
		OleMenuCommand OleMenuCommandScan;
		OleMenuCommand OleMenuCommandRemove;
		OleMenuCommand OleMenuCommandReport;
		bool boolAreReferencesBeingScanned;
		UserControlSolutionTree UserControlSolutionTreeInstance;
		private bool AreReferencesBeingScanned
		{
			get
			{
				return boolAreReferencesBeingScanned;
			}
			set
			{
				if(value != boolAreReferencesBeingScanned)
				{
					boolAreReferencesBeingScanned = value;
					EnableDisableScanningUnusedReferences();
					EnableDisableRemovingUnusedReferences();
				}
			}
		}
		int intCompletedActionsCount = 0;
		const int intAdditionalActionsCount = 2;
		int intActualActionsCount = 0;
		List<String> ListOfScannedAssemblies = new List<string>();
		Hashtable HashtableScanningSettingsForDisplay;

		#endregion

		#region Constructors

		/// <summary>
		/// Default constructor of the package.
		/// Inside this method you can place any initialization code that does not require 
		/// any Visual Studio service because at this point the package object is created but 
		/// not sited yet inside Visual Studio environment. The place to do all the other 
		/// initialization is the Initialize method.
		/// </summary>
		public PackageUnusedReferences()
		{
			DebugHelper.LogCall();
		}

		#endregion

		#region Helper Functions

		private void RefreshNodes()
		{
			DebugHelper.LogCall();
			if(SolutionTree != null)
			{
				//SolutionTree.SaveSelection();
				SolutionTree.RefreshNodes(HashtableProjectUsedReferencedAssemblis);
				//SolutionTree.LoadSelection(false);
			}
		}
		private void ClearNodes()
		{
			DebugHelper.LogCall();
			if(SolutionTree != null)
			{
				SolutionTree.ClearNodes();
			}
		}
		private void RemoveSelectedReferences()
		{
			DebugHelper.LogCall();
			if(SolutionTree != null)
			{
				IntPtr IntPtrBitmapStrip = Resources.Delete.GetHbitmap();
				Logger.StartStatusBarAnimation(IntPtrBitmapStrip);
				#region Prevent Phantom problem

				SolutionTree.SaveSelection();
				ScanUnusedReferences();
				SolutionTree.LoadSelection(true);

				#endregion
				SolutionTree.RemoveSelectedReferences();
				EnableDisableRemovingUnusedReferences();
				Logger.EndStatusBarAnimation(IntPtrBitmapStrip);
			}
		}
		private void ReportUnusedReferences()
		{
			DebugHelper.LogCall();
			if(SolutionTree == null)
			{
				//Should be a message for the user.
				return;
			}
			//HashtableSettingsForDisplay[DialogPageOptions.IncludeSelectionInExportedFile_DisplayName] = Options.IncludeSelectionInExportedFile ? "Yes" : "No";
			System.Windows.Forms.FolderBrowserDialog FolderBrowserdialogReport = new System.Windows.Forms.FolderBrowserDialog();
			if(FolderBrowserdialogReport.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				string stringDefaultFilePath = SolutionTree.ReportUnusedReferences(FolderBrowserdialogReport.SelectedPath, dte.Solution.Properties.Item("Name").Value.ToString(), HashtableScanningSettingsForDisplay);
				if(System.Windows.Forms.MessageBox.Show("Do you want to view the exported file now ?", "Export", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question, System.Windows.Forms.MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
				{
					try
					{
						System.Diagnostics.Process.Start(stringDefaultFilePath);
					}
					catch(Exception Ex)
					{
						System.Windows.Forms.MessageBox.Show(Ex.Message);
					}
				}
			}
		}
		private void EnableDisableScanningUnusedReferences()
		{
			DebugHelper.LogCall();
			OleMenuCommandScan.Enabled = (SelectionEvents.SolutionHasSingleProject || SelectionEvents.SolutionHasMultipleProjects) && !SelectionEvents.Debugging && !AreReferencesBeingScanned;
		}
		private void EnableDisableRemovingUnusedReferences()
		{
			DebugHelper.LogCall();
			OleMenuCommandRemove.Enabled = (SelectionEvents.SolutionHasSingleProject || SelectionEvents.SolutionHasMultipleProjects) && !SelectionEvents.Debugging && !AreReferencesBeingScanned && SolutionTree != null && SolutionTree.NumberOfCheckedReferences > 0;
		}
		private void EnableDisableReportingUnusedReferences()
		{
			DebugHelper.LogCall();
			OleMenuCommandReport.Enabled = (SelectionEvents.SolutionHasSingleProject || SelectionEvents.SolutionHasMultipleProjects) && !SelectionEvents.Debugging && !AreReferencesBeingScanned && SolutionTree != null && SolutionTree.NumberOfNodes > 0;
		}
		private void ClearTrashSolutionConfigurations()
		{
			DebugHelper.LogCall();
			for(int intConfigIndex = 1; intConfigIndex <= dte.Solution.SolutionBuild.SolutionConfigurations.Count; intConfigIndex++)
			{
				if(dte.Solution.SolutionBuild.SolutionConfigurations.Item(intConfigIndex).Name.EndsWith(stringSolutionConfigurationSuffix))
				{
					dte.Solution.SolutionBuild.SolutionConfigurations.Item(intConfigIndex).Delete();
					intConfigIndex--;
				}
			}
		}
		private UserControlSolutionTree GetMainControl(bool CreateIfNull)
		{
			DebugHelper.LogCall();
			ToolWindowPane window = FindToolWindow(typeof(ToolWindowSolutionTree), 0, CreateIfNull);
			if((null == window) || (null == window.Frame))
			{
				return null;
			}
			IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame;
			//Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show());
			if(windowFrame.Show() == VSConstants.S_OK)
			{
				return ((ToolWindowSolutionTree)window).SolutionTree;
			}
			return null;
		}
		private void InitializeMyOutputWindowPane()
		{
			DebugHelper.LogCall();
			// Now print the string on the output window.
			// The first step is to get a reference to IVsOutputWindow.
			IVsOutputWindow outputWindow = GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow;

			// If we fail to get it we can exit now.
			if(null == outputWindow)
			{
				Trace.WriteLine("Failed to get a reference to IVsOutputWindow");
				return;
			}

			// Now get the window pane for the general output.
			Guid guidGeneral = VSConstants.GUID_OutWindowGeneralPane;

			// following instructions on MEF Output Window forum. if this doesn't work, use the commented out stuff below this
			if(ErrorHandler.Failed(outputWindow.GetPane(ref guidGeneral, out MyOutputWindowPane)) && (ErrorHandler.Succeeded(outputWindow.CreatePane(ref guidGeneral, "Unused References", 1, 1))))
			{
				outputWindow.GetPane(ref guidGeneral, out MyOutputWindowPane);
			}
			//if (Microsoft.VisualStudio.ErrorHandler.Failed(outputWindow.GetPane(ref guidGeneral, out windowPane)))
			//{
			//    Trace.WriteLine("Failed to get a reference to the Output Window General pane");
			//    return;
			//}

			// following instructions on MEF Output Window forum. if this doesn't work, use the commented out stuff below this
			//if (Microsoft.VisualStudio.ErrorHandler.Failed(windowPane.OutputString(outputText.ToString())))
			//{
			//    Trace.WriteLine("Failed to write on the output window");
			//}
		}
		private void WriteToMyOutputWindowPane(string stringMessage)
		{
			DebugHelper.LogCall();
			if(MyOutputWindowPane == null)
			{
				return;
			}
			MyOutputWindowPane.Activate();
			MyOutputWindowPane.OutputString(stringMessage + "\n");
		}
		private void ReportProgress(string Message)
		{
			DebugHelper.LogCall();
			Logger.LogStatusBarProgress(1, Message, (uint)intCompletedActionsCount, (uint)(intAdditionalActionsCount + intActualActionsCount));
		}
		private void ScanUnusedReferences()
		{
			DebugHelper.LogCall();
			AreReferencesBeingScanned = true;
			intCompletedActionsCount = 0;
			Logger.SetTextInsertionMode(Enums.UIE_TEXTINSMODE.UIE_TEXTINSMODE_INSERT);
			SolutionConfiguration SolutionConfigurationCurrentActive = null;
			IntPtr IntPtrBitmapStrip = Resources.Scan.GetHbitmap();
			Logger.StartStatusBarAnimation(IntPtrBitmapStrip);

			if(!dte.Solution.SolutionBuild.ActiveConfiguration.Name.EndsWith(stringSolutionConfigurationSuffix))
			{
				SolutionConfigurationCurrentActive = dte.Solution.SolutionBuild.ActiveConfiguration;
			}
			try
			{
				MyOutputWindowPane.Clear();
				WriteToMyOutputWindowPane("Start detecting unused references...");
				ClearTrashSolutionConfigurations();
				if(ScanUnusedReferencesCore())
				{
					RefreshNodes();
				}
				else
				{
					ClearNodes();
				}
				ClearTrashSolutionConfigurations();
				WriteToMyOutputWindowPane("Done with help from ALLAH");
				HashtableScanningSettingsForDisplay = Options.GetSettingsForDisplay(SettingsCategory.Scanning);
			}
			catch
			{
				throw;
			}
			finally
			{
				if(SolutionConfigurationCurrentActive != null)
				{
					SolutionConfigurationCurrentActive.Activate();
				}
				intCompletedActionsCount++;//For second additional action.
				ReportProgress("Finished scanning unused references");
				Logger.EndStatusBarAnimation(IntPtrBitmapStrip);
				Logger.HideProgressBar();
				AreReferencesBeingScanned = false;
			}
		}
		private bool ScanUnusedReferencesCore()
		{
			DebugHelper.LogCall();
			HashtableProjectUsedReferencedAssemblis.Clear();
			List<string> SolutionConfigurationsCurrent = new List<string>();
			ListOfScannedAssemblies.Clear();

			for(int intConfigIndex = 1; intConfigIndex <= dte.Solution.SolutionBuild.SolutionConfigurations.Count; intConfigIndex++)
			{
				if(dte.Solution.SolutionBuild.SolutionConfigurations.Item(intConfigIndex).Name.EndsWith(stringSolutionConfigurationSuffix))
				{
					dte.Solution.SolutionBuild.SolutionConfigurations.Item(intConfigIndex).Delete();
					intConfigIndex--;
				}
				else if(!SolutionConfigurationsCurrent.Contains(dte.Solution.SolutionBuild.SolutionConfigurations.Item(intConfigIndex).Name))
				{
					SolutionConfigurationsCurrent.Add(dte.Solution.SolutionBuild.SolutionConfigurations.Item(intConfigIndex).Name);
				}
			}
			intActualActionsCount = SolutionConfigurationsCurrent.Count;
			intCompletedActionsCount++;//For first additional action.
			ReportProgress("Start scanning unused references");
			foreach(string stringSolutionConfigurationCurrent in SolutionConfigurationsCurrent)
			{
				SolutionConfiguration SolutionConfigurationNew = dte.Solution.SolutionBuild.SolutionConfigurations.Add(string.Format("{0}{1}", stringSolutionConfigurationCurrent, stringSolutionConfigurationSuffix), stringSolutionConfigurationCurrent, false);
				foreach(SolutionContext SolutionContextInstance in SolutionConfigurationNew.SolutionContexts)
				{
					SolutionContextInstance.ShouldBuild = SolutionContextInstance.ShouldBuild || !Options.ScanBuildableProjectsOnly;
					SolutionContextInstance.ShouldDeploy = false;
				}
				SolutionConfigurationNew.Activate();
				WriteToMyOutputWindowPane(string.Format("Building '{0}'...", SolutionConfigurationNew.Name.Replace(stringSolutionConfigurationSuffix, string.Empty)));
				ReportProgress(string.Format("Building '{0}'...", SolutionConfigurationNew.Name));
				Logger.FreezeOutput(true);
				dte.Solution.SolutionBuild.Build(true);
				Logger.FreezeOutput(false);
				if(dte.Solution.SolutionBuild.LastBuildInfo > 0)
				{
					WriteToMyOutputWindowPane("Can not continue due to build errors.");
					return false;
				}
				else
				{
					ScanSolutionConfiguration(SolutionConfigurationNew);
					WriteToMyOutputWindowPane(string.Format("'{0}' scanned successfully.", SolutionConfigurationNew.Name.Replace(stringSolutionConfigurationSuffix, string.Empty)));
				}
			}
			return true;
		}
		private void ScanSolutionConfiguration(SolutionConfiguration SolutionConfigurationInstance)
		{
			DebugHelper.LogCall();
			ReportProgress(string.Format("Scanning '{0}'...", SolutionConfigurationInstance.Name.Replace(stringSolutionConfigurationSuffix, string.Empty)));
			foreach(SolutionContext SolutionContextInstance in SolutionConfigurationInstance.SolutionContexts)
			{
				if(SolutionContextInstance.ShouldBuild)
				{
					ScanProjectForUsedReferencedAssemblies(SolutionContextInstance.ProjectName, SolutionContextInstance.ConfigurationName, SolutionContextInstance.PlatformName);
				}
			}
			intCompletedActionsCount++;
		}
		private void ScanProjectForUsedReferencedAssemblies(string ProjectName, string ConfigurationName, string PlatformName)
		{
			DebugHelper.LogCall();
			foreach(Project ProjectInstance in dte.Solution.Projects)
			{
				if(ProjectInstance.UniqueName == ProjectName)
				{
					foreach(Configuration ConfigurationInstance in ProjectInstance.ConfigurationManager)
					{
						if(ConfigurationInstance.ConfigurationName == ConfigurationName && ConfigurationInstance.PlatformName == PlatformName)
						{
							AddUsedReferencedAssemblies(ProjectInstance, ConfigurationInstance);
							return;
						}
					}
				}
			}
		}
		private void AddUsedReferencedAssemblies(Project ProjectInstance, Configuration ConfigurationInstance)
		{
			DebugHelper.LogCall();
			string stringAssemblyPath = ProjectInstance.GetAssemblyPath(ConfigurationInstance);
			if(ListOfScannedAssemblies.Contains(stringAssemblyPath))
			{
				return;
			}
			else
			{
				ListOfScannedAssemblies.Add(stringAssemblyPath);
			}
			ReportProgress(string.Format("Scanning {0} ({1})", ProjectInstance.Name, ConfigurationInstance.ConfigurationName.Replace(stringSolutionConfigurationSuffix, string.Empty)));
			AssemblyName[] UsedReferencedAssemblies = null;
			List<AssemblyName> ProjectUsedReferencedAssemblies = (List<AssemblyName>)HashtableProjectUsedReferencedAssemblis[ProjectInstance.FullName];
			if(ProjectUsedReferencedAssemblies == null)
			{
				UsedReferencedAssemblies = ProjectInstance.GetReferencedAssemblies(ConfigurationInstance, new AssemblyName[] { });
				ProjectUsedReferencedAssemblies = new List<AssemblyName>();
				ProjectUsedReferencedAssemblies.AddRange(UsedReferencedAssemblies);
				HashtableProjectUsedReferencedAssemblis.Add(ProjectInstance.FullName, ProjectUsedReferencedAssemblies);
			}
			else
			{
				UsedReferencedAssemblies = ProjectInstance.GetReferencedAssemblies(ConfigurationInstance, ProjectUsedReferencedAssemblies.ToArray());
				ProjectUsedReferencedAssemblies.AddRangeEx(UsedReferencedAssemblies);
			}
		}
		private void AddUsedReferencedAssemblies(Project ProjectInstance, string[] UsedReferencedAssemblies)
		{
			DebugHelper.LogCall();
			List<string> ProjectUsedReferencedAssemblies = (List<string>)HashtableProjectUsedReferencedAssemblis[ProjectInstance.FullName];
			if(ProjectUsedReferencedAssemblies == null)
			{
				ProjectUsedReferencedAssemblies = new List<string>();
				ProjectUsedReferencedAssemblies.AddRange(UsedReferencedAssemblies);
				HashtableProjectUsedReferencedAssemblis.Add(ProjectInstance.FullName, ProjectUsedReferencedAssemblies);
			}
			else
			{
				ProjectUsedReferencedAssemblies.AddRangeEx(UsedReferencedAssemblies);
			}
		}

		#endregion

		#region Overriden Members

		protected override void Dispose(bool disposing)
		{
			DebugHelper.LogCall();
			base.Dispose(disposing);
			SelectionEvents.Dispose();
			SolutionEvents.Dispose();
			UpdateSolutionEvents2.Dispose();
		}
		/// <summary>
		/// Initialization of the package; this method is called right after the package is sited, so this is the place
		/// where you can put all the initilaization code that rely on services provided by VisualStudio.
		/// </summary>
		protected override void Initialize()
		{
			DebugHelper.LogCall();
			base.Initialize();
			SelectionEvents = new VsSelectionEvents();
			SolutionEvents = new VsSolutionEvents();
			SolutionEvents.AfterCloseSolution += new EventHandler(SolutionEvents_AfterCloseSolution);
			// Add our command handlers for menu (commands must exist in the .vsct file)
			OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
			if(null != mcs)
			{
				CommandID CommandIDScan = new CommandID(GuidList.guidUnusedReferencesCmdSet, PkgCmdIDList.CommandIDScan);
				OleMenuCommandScan = new OleMenuCommand(OleMenuCommandScan_Handler, CommandIDScan);
				OleMenuCommandScan.BeforeQueryStatus += new EventHandler(OleMenuCommandScan_BeforeQueryStatus);
				mcs.AddCommand(OleMenuCommandScan);

				CommandID CommandIDShowToolWindow = new CommandID(GuidList.guidUnusedReferencesCmdSet, PkgCmdIDList.CommandIDShowToolWindow);
				OleMenuCommandShowToolWindow = new OleMenuCommand(OleMenuCommandShowToolWindow_Handler, CommandIDShowToolWindow);
				OleMenuCommandShowToolWindow.BeforeQueryStatus += new EventHandler(OleMenuCommandShowToolWindow_BeforeQueryStatus);
				mcs.AddCommand(OleMenuCommandShowToolWindow);

				CommandID CommandIDRemove = new CommandID(GuidList.guidUnusedReferencesCmdSet, PkgCmdIDList.CommandIDRemove);
				OleMenuCommandRemove = new OleMenuCommand(OleMenuCommandRemove_Handler, CommandIDRemove);
				OleMenuCommandRemove.BeforeQueryStatus += new EventHandler(OleMenuCommandRemove_BeforeQueryStatus);
				mcs.AddCommand(OleMenuCommandRemove);

				CommandID CommandIDReport = new CommandID(GuidList.guidUnusedReferencesCmdSet, PkgCmdIDList.CommandIDReport);
				OleMenuCommandReport = new OleMenuCommand(OleMenuCommandReport_Handler, CommandIDReport);
				OleMenuCommandReport.BeforeQueryStatus += new EventHandler(OleMenuCommandReport_BeforeQueryStatus);
				mcs.AddCommand(OleMenuCommandReport);


			}
			dte = ServiceProvider.GlobalProvider.GetService(typeof(SDTE)) as DTE2;
			InitializeMyOutputWindowPane();
			Options = (DialogPageOptionsGeneral)GetDialogPage(typeof(DialogPageOptionsGeneral));
			DialogPageOptionsReset OptionsReset = (DialogPageOptionsReset)GetDialogPage(typeof(DialogPageOptionsReset));
			OptionsReset.Options = Options;
			//UIContextGuids.SolutionHasSingleProject
		}

		void SolutionEvents_AfterCloseSolution(object sender, EventArgs e)
		{
			DebugHelper.LogCall();
			ClearNodes();
		}

		#endregion

		#region Properties

		internal static VsSelectionEvents SelectionEvents
		{
			get;
			private set;
		}
		internal static VsShellPropertyEvents ShellPropertyEvents
		{
			get;
			private set;
		}
		internal static VsSolutionEvents SolutionEvents
		{
			get;
			private set;
		}
		internal static VsUpdateSolutionEvents2 UpdateSolutionEvents2
		{
			get;
			private set;
		}
		private UserControlSolutionTree SolutionTree
		{
			get
			{
				DebugHelper.LogCall();
				if(UserControlSolutionTreeInstance == null)
				{
					UserControlSolutionTreeInstance = GetMainControl(false);
					if(UserControlSolutionTreeInstance != null)
					{
						UserControlSolutionTreeInstance.ItemCheckedChanged += new EventHandler(UserControlSolutionTreeInstance_ItemCheckedChanged);
						UserControlSolutionTreeInstance.Options = Options;
					}
				}
				return UserControlSolutionTreeInstance;
			}
		}
		
		#endregion

		#region Events' Handlers

		private void OleMenuCommandScan_BeforeQueryStatus(object sender, EventArgs e)
		{
			DebugHelper.LogCall();
			EnableDisableScanningUnusedReferences();
		}
		private void OleMenuCommandRemove_BeforeQueryStatus(object sender, EventArgs e)
		{
			DebugHelper.LogCall();
			EnableDisableRemovingUnusedReferences();
		}
		private void OleMenuCommandReport_BeforeQueryStatus(object sender, EventArgs e)
		{
			DebugHelper.LogCall();
			EnableDisableReportingUnusedReferences();
		}
		private void OleMenuCommandShowToolWindow_BeforeQueryStatus(object sender, EventArgs e)
		{
			DebugHelper.LogCall();
			OleMenuCommandShowToolWindow.Visible = SelectionEvents.SolutionHasSingleProject || SelectionEvents.SolutionHasMultipleProjects;
			//foreach(EnvDTE.Project dteProject in dte.Solution.Projects)
			//{
			//    Guid SolutionFolder = new Guid(EnvDTE.Constants.vsProjectKindSolutionItems);
			//    Guid MiscellaneousFiles = new Guid(EnvDTE.Constants.vsProjectKindMisc);
			//    Guid currentProjectKind = new Guid(dteProject.Kind);
			//    if(currentProjectKind != SolutionFolder && currentProjectKind != MiscellaneousFiles)
			//    {
			//        //menuVisible = true;
			//    }
			//}


		}
		private void OleMenuCommandScan_Handler(object sender, EventArgs e)
		{
			DebugHelper.LogCall();
			//if(hierarchy == null)
			//{
			//    return VSConstants.E_INVALIDARG;
			//}
			ScanUnusedReferences();
		}
		private void OleMenuCommandRemove_Handler(object sender, EventArgs e)
		{
			DebugHelper.LogCall();
			RemoveSelectedReferences();
		}
		private void OleMenuCommandReport_Handler(object sender, EventArgs e)
		{
			DebugHelper.LogCall();
			ReportUnusedReferences();
		}
		private void OleMenuCommandShowToolWindow_Handler(object sender, EventArgs e)
		{
			DebugHelper.LogCall();
			// Get the instance number 0 of this tool window. This window is single instance so this instance
			// is actually the only one.
			// The last flag is set to true so that if the tool window does not exists it will be created.
			ToolWindowPane window = FindToolWindow(typeof(ToolWindowSolutionTree), 0, true);
			if((null == window) || (null == window.Frame))
			{
				throw new NotSupportedException(Resources.CanNotCreateWindow);
			}
			IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame;
			Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show());
		}
		private void UserControlSolutionTreeInstance_ItemCheckedChanged(object sender, EventArgs e)
		{
			DebugHelper.LogCall();
			EnableDisableRemovingUnusedReferences();
		}

		#endregion
	}
}